package com.baizhi.cmfz.realm;

import com.baizhi.cmfz.dao.AdminDao;
import com.baizhi.cmfz.entity.Admin;
import com.baizhi.cmfz.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private RoleService roleService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
      //获取用户名
       String username= (String) principals.getPrimaryPrincipal();
       //通过用户名查询授权数据
        Set<String> permissions=roleService.getAllPermissionsByUserName(username);
        System.out.println("---------"+permissions);
        Set<String> roles=roleService.getAllRolesByUserName(username);
        //封装info
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        UsernamePasswordToken token1= (UsernamePasswordToken) token;
        String username=token1.getUsername();
        //查询数据库
        Admin admin=adminDao.showNameAndPwd(username);
        //封装info
        if(admin!=null){
            return  new SimpleAuthenticationInfo(admin.getUsername(),admin.getPassword(),this.getName());
        }
        return null;
    }
}
